package com.yin.user.controller;

import java.util.List;
import java.util.Optional;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yin.user.entity.UserEntity;
import com.yin.user.jpa.UserJPA;

/**
*@author LSY
*Time: 2018年12月26日上午11:29:45
*
*
*/
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserJPA userJPA;
	@GetMapping(value = "/{id}")
	public UserEntity getUserById(@PathVariable Long id) {
		Optional<UserEntity> op = userJPA.findById(id);
		if(op.isPresent()) {
			return op.get();
		}
		return new UserEntity();
	}
	@GetMapping(value = "/all")
	public List<UserEntity> findAll(int page){
		UserEntity user = new UserEntity();
		user.setPage(page);
		user.setSize(2);
		user.setSord("desc");
		
		Sort.Direction sort_derection = Sort.Direction.ASC.toString().equalsIgnoreCase(user.getSord())? Sort.Direction.ASC : Sort.Direction.DESC;
		Sort sort = new Sort(sort_derection, user.getSidx());
		PageRequest pageRequest = new PageRequest(user.getPage() - 1, user.getSize(), sort);
		return userJPA.findAll(pageRequest).getContent();
	}
	@GetMapping(value = "/password")
	public List<UserEntity> findUserByPassword(String password){
		return userJPA.nativeQuery(password);
	}
	@GetMapping(value = "/delete")
	public void del(Long id) {
		userJPA.deleteById(id);
	}
	
	@GetMapping(value = "/save")
	public UserEntity add(UserEntity user) {
		userJPA.save(user);
		return user;
	}
	@GetMapping(value = "del")
	public String add(String name) {
		userJPA.deleteQuery(name);
		return "success";
	}
}
